package main

import (
	"DistributeCalculator/task"
	"sync"
)

type taskQueen struct {
	taskWaitingQueen []*task.ClientRequest
	taskResultQueen  []*task.WorkerResponse
	mutex            sync.Mutex
}

//======================对任务等待队列进行操作=====================//
func (this *taskQueen) TaskWaitingQueenSize() int {
	this.mutex.Lock()
	length := len(this.taskWaitingQueen)
	this.mutex.Unlock()
	return length
}

func (this *taskQueen) TaskWaitingPush(request *task.ClientRequest) {
	this.mutex.Lock()
	this.taskWaitingQueen = append(this.taskWaitingQueen, request)
	this.mutex.Unlock()
}

func (this *taskQueen) TaskWaitingPop() *task.ClientRequest {
	length := this.TaskWaitingQueenSize()

	if length > 0 {
		this.mutex.Lock()

		req := this.taskWaitingQueen[length-1]
		this.taskWaitingQueen = this.taskWaitingQueen[:length-1]

		this.mutex.Unlock()
		return req
	} else {
		return nil
	}

}

func (this *taskQueen) GetLastWaitingTask() *task.ClientRequest {
	length := this.TaskWaitingQueenSize()
	if length > 0 {
		req := this.taskWaitingQueen[length-1]
		return req
	} else {
		return nil
	}

}

//======================对任务结果队列进行操作====================//
func (this *taskQueen) TaskResultQueenSize() int {
	this.mutex.Lock()
	length := len(this.taskResultQueen)
	this.mutex.Unlock()
	return length
}

func (this *taskQueen) TaskResultPush(request *task.WorkerResponse) {
	this.mutex.Lock()
	defer this.mutex.Unlock()

	this.taskResultQueen = append(this.taskResultQueen, request)
}

func (this *taskQueen) TaskResultPop() *task.WorkerResponse {
	length := this.TaskResultQueenSize()
	if length > 0 {
		this.mutex.Lock()

		req := this.taskResultQueen[length-1]
		this.taskResultQueen = this.taskResultQueen[:length-1]

		this.mutex.Unlock()
		return req
	} else {
		return nil
	}
}

func (this *taskQueen) selectResult(taskId *task.TaskID) ([]*task.WorkerResponse, error) {

	rq := this.taskResultQueen
	var wr []*task.WorkerResponse
	for _, r := range rq {
		if r.GetTask().GetTaskID().GetTaskID() == taskId.GetTaskID() {
			wr = append(wr, r)
		}
	}

	return wr, nil
}
